import {Component, OnInit} from '@angular/core';
import {AliyunOssOutputUrl} from '../../../../config/api';
import {ActivatedRoute, Router} from '@angular/router';
import {isInteger} from '@ng-bootstrap/ng-bootstrap/util/util';
import {Observable} from 'rxjs/Observable';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import * as moment from 'moment';
import {GroupService} from '../group.service';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss'],
  providers: [GroupService]
})
export class EditComponent implements OnInit {

  validateForm: FormGroup;
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  groupName;
  _isSpinning = false;
  start_date = null;
  end_date = null;
  random_free = null;
  randomStatus = false;
  isNewGroup;  // 是否为拉新拼团
  disabledClick = false;
  stage; // 团进行状态 1-未开始 2-进行中 3-已结束
  hasCheckedSku = true;
  activity_goods_prize;
  queryParams: any;
  saveStatus = '';
  /* 商品弹窗 */
  goodsModalVisible = false;
  goodsList = [];
  groupList = [];
  selectedGroup;
  keyword;
  currentClickGoods = {};
  checkedGoodsInfo = {};
  page = 1;
  pageSize = 5;
  total;
  loading = false;
  status = '上架';
  highPriceSkuId = 0;
  currentGoodsPrice = 0;
  disabledNewGroup = false;
  ghostData = null; //code6000 reset
  nosupportClick = true;

  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  }
  _startValueChange = () => {
    if (this.start_date > this.end_date) {
      this.end_date = null;
    }
  }
  _endValueChange = () => {
    if (this.start_date > this.end_date) {
      this.start_date = null;
    }
  }
  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!startValue || !this.validateForm.value.validity_end) {
      return startValue < now_time;
    }
    return (startValue.getTime() >= this.validateForm.value.validity_end.getTime()) || (startValue.getTime() <= Date.now());
  }
  _disabledEndDate = (endValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    const now_time = now.getTime();
    if (!endValue || !this.start_date) {
      return endValue.getTime() < now_time;
    }
    return endValue.getTime() < this.start_date.getTime();
  }

  get _isSameDay() {
    return this.start_date && this.end_date && moment(this.start_date).isSame(this.end_date, 'day');
  }

  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this.start_date.getHours()) : [];
      },
      nzDisabledMinutes: (h) => {
        if (this._isSameDay && h === this.start_date.getHours()) {
          return this.newArray(this.start_date.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (this._isSameDay && h === this.start_date.getHours() && m === this.start_date.getMinutes()) {
          return this.newArray(this.start_date.getSeconds());
        }
        return [];
      }
    };
  }

  // 整数验证
  integerValidators = (control: FormControl) => {
    return Observable.create(function (observer) {
      if (!isInteger(control.value)) {
        observer.next({error: true, notInteger: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  }

  //价格验证
  priceValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (control.value > this.currentGoodsPrice) {
        observer.next({error: true, priceToHigh: true});
      } else {
        observer.next(null);
      }
      observer.complete();
    })
  };

  winnerNumValidator = (control: FormControl) => {
    if (!control.value) {
      return {required: true};
    } else if (!!this.validateForm.value.number && control.value > this.validateForm.value.number) {
      return ({error: true, more: true});
    }
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  constructor(private fb: FormBuilder,
              private groupService: GroupService,
              private route: ActivatedRoute,
              private router: Router,
              private _message: NzMessageService,
  ) {
    this.validateForm = this.fb.group({
      id: [null, [Validators.required]],
      activity_goods_id: [null, Validators.required],
      group_type: [null, [Validators.required]],
      name: ['', [Validators.required, Validators.maxLength(30)]],
      goods_id: [null, [Validators.required]],
      number: [null, [Validators.required, Validators.min(2), Validators.max(20)], [this.integerValidators]],
      price: ['', [Validators.required, Validators.min(0.01), Validators.max(99999999)], [this.priceValidators]],
      round: [null, [Validators.required, Validators.min(0), Validators.max(999)], [this.integerValidators]],
      start_date: [null, [Validators.required]],
      end_date: [null, [Validators.required]],
      new_offer: [false, [Validators.required]],
      is_show: [true, [Validators.required]],
      sorts: [null, [Validators.required, Validators.min(0), Validators.max(99)], [this.integerValidators]]
      // winners_number: ['', [this.winnerNumValidator], [this.integerValidators]],
      // free_scale: [null, [Validators.required, Validators.max(100)], [this.integerValidators]],
      // head_win: [false, [Validators.required]],
    });
  }

  ngOnInit() {
    const id = +this.route.snapshot.params['id'];
    this.getGroupInfo(id);
    this.getGroupList();
    if (this.route.snapshot.queryParams['stage'] == '2') {
      this.saveStatus = '1';
    } else if (this.route.snapshot.queryParams['stage'] == '4') {
      this.saveStatus = '2';
    } else {
      this.saveStatus = '';
    }
  }

  // 获取拼团详情
  getGroupInfo(id) {
    this.groupService.getActivityInfo(id).subscribe(res => {
      if (res.code === 2000) {
        const data = res.data;
        this.ghostData = data;
        this.stage = data.stage;
        if (data.group_type === 1 || data.group_type === 4) {
          this.groupName = '普通拼团';
          this.isNewGroup = false;
        }
        if (data.group_type === 1) {
          if (data.free_scale) {
            this.random_free = 1;
          } else {
            this.random_free = 0;
          }
          this.changeRandomFreeGroup();
        } else if (data.group_type === 4) {
          this.random_free = 2;
          this.changeRandomFreeGroup();
        } else {
          this.groupName = '拉新拼团';
          this.isNewGroup = true;
          this.validateForm.removeControl('winners_number');
          this.validateForm.removeControl('free_scale');
          this.validateForm.removeControl('head_win');
          this.validateForm.removeControl('head_free_price');
          this.validateForm.removeControl('is_give');
        }
        let nowTime = new Date().getTime();
        if (nowTime > new Date(data.start_date).getTime()) {
          this.disabledNewGroup = true;
        }
        const startDate = new Date(data.start_date + ' 00:00:00');
        const endDate = new Date(data.end_date + ' 23:59:59');
        this.validateForm.controls['id'].setValue(data.id);
        this.validateForm.controls['activity_goods_id'].setValue(data.activity_goods_id);
        this.validateForm.controls['group_type'].setValue(data.group_type);
        this.validateForm.controls['name'].setValue(data.name);
        this.validateForm.controls['goods_id'].setValue(data.activity_goods.goods_id);
        this.validateForm.controls['number'].setValue(data.number);
        this.validateForm.controls['price'].setValue(data.activity_goods.price / 1000);
        this.validateForm.controls['round'].setValue(data.round);
        this.validateForm.controls['start_date'].setValue(startDate);
        this.validateForm.controls['end_date'].setValue(endDate);
        this.validateForm.controls['new_offer'].setValue(data.new_offer ? true : false);
        this.validateForm.controls['is_show'].setValue(data.is_show ? true : false);
        this.validateForm.controls['sorts'].setValue(data.sorts);
        const goodsInfo = data.activity_goods;
        this.checkedGoodsInfo = {
          id: goodsInfo.goods_id,
          name: goodsInfo.name,
          first_picture: goodsInfo.picture,
          sku: goodsInfo.goods_sku,
          in_stock: goodsInfo.in_stock
        };
        const activity_goods_prize = [];
        goodsInfo.goods_sku.every((val, idx, array) => {
          goodsInfo.activity_goods_sku.every((val1, idx1, array1) => {
            if (val1.goods_sku_id === val.id) {
              val.checked = true;
              let skuPrice = val1.price / 1000;
              if (skuPrice > this.currentGoodsPrice) {
                this.currentGoodsPrice = skuPrice;
              }
              const sku_item = {'sku_id': val.id, 'number': val.in_stock};
              activity_goods_prize.push(sku_item);
            }
            return true;
          });
          return true;
        });
        this.activity_goods_prize = activity_goods_prize;
        let prevValue = this.validateForm.get('price').value;
        this.validateForm.removeControl('price');
        this.validateForm.addControl('price', this.fb.control(prevValue, [Validators.required, Validators.min(0.01), Validators.max(99999999)], [this.priceValidators]))
        this.groupService.getbindListAll(goodsInfo.goods_id).subscribe(rs => {
          if (rs.code === 2000) {
            this.checkedGoodsInfo['goods_category'] = rs.data;
          } else {
            this._message.create('error', rs.message);
          }
        });
      }
    });
  }

  // 添加商品
  addGoods() {
    this.currentClickGoods = JSON.parse(JSON.stringify(this.checkedGoodsInfo));
    this.goodsModalVisible = true;
    this.getGoodsList();
  }

  // 关闭添加商品弹窗
  closeModal() {
    this.currentClickGoods = JSON.parse(JSON.stringify(this.checkedGoodsInfo));
    this.goodsModalVisible = false;
  }

  // 确认选择商品
  confirmCheckedGoods() {
    this.checkedGoodsInfo = JSON.parse(JSON.stringify(this.currentClickGoods));
    this.validateForm.controls['goods_id'].setValue(this.currentClickGoods['id']);
    // 获取选择商品的sku
    this.groupService.getGoodsSkuList(this.currentClickGoods['id'], 100).subscribe(res => {
      if (res.code === 2000) {
        const sku = res.data.data;
        const activity_goods_prize = [];
        sku.every((val, idx, array) => {
          val.checked = true;
          const sku_item = {'sku_id': val.id, 'number': val.in_stock};
          activity_goods_prize.push(sku_item);
          return true;
        });
        this.activity_goods_prize = activity_goods_prize;
        this.checkedGoodsInfo['sku'] = sku;
        this.currentGoodsPrice = 0;
        let price = 0;
        this.checkedGoodsInfo['sku'].map((e, i) => {
          let skuPrice = e.price / 1000;
          if (skuPrice > price) {
            price = skuPrice;
            this.highPriceSkuId = e.id;
          }
        });
        this.currentGoodsPrice = price;
        let value = parseFloat(this.validateForm.get('price').value);
        this.validateForm.removeControl('price');
        this.validateForm.addControl('price', this.fb.control(value, [Validators.required, Validators.min(0.01), Validators.max(99999999)], [this.priceValidators]));
        this.goodsModalVisible = false;
      } else {
        this._message.create('error', res.message);
      }
    });
    this.goodsModalVisible = false;
  }

  // 处理商品的sku
  dealSku() {
    const activity_goods_prize = [];
    if (!!this.checkedGoodsInfo['sku'].length) {
      this.checkedGoodsInfo['sku'].every((val, idx, array) => {
        if (val.checked) {
          const sku_item = {'sku_id': val.id, 'number': val.in_stock};
          activity_goods_prize.push(sku_item);
        }
        return true;
      });
      this.activity_goods_prize = activity_goods_prize;
      if (!activity_goods_prize.length) {
        this.hasCheckedSku = false;
      } else {
        this.hasCheckedSku = true;
      }
    }
  }

  // 获取店铺商品类型列表
  getGroupList() {
    this.groupService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
    });
  }

  // 获取商品列表
  getGoodsList() {
    this.loading = true;
    this.groupService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.keyword, this.status).subscribe(res => {
      if (res.code === 2000) {
        this.total = res.data.total;
        const goodsList = res.data.data;
        const goodsId = [];
        goodsList.forEach(item => {
          goodsId.push(item.id);
        });
        this.groupService.getbindListAll('[' + goodsId.join(',') + ']').subscribe(rs => {
          if (rs.code === 2000) {
            const goodsjson = {};
            rs.data.forEach(item => {
              if (!goodsjson[item.goods_id]) {
                goodsjson[item.goods_id] = [item.name];
              } else {
                goodsjson[item.goods_id].push(item.name);
              }
            });
            goodsList.forEach(item => {
              if (item.goods_number) {
                item.goods_number = item.goods_number.split('|');
              }
              item.goods_category = goodsjson[item.id];
            });
          }
          this.goodsList = goodsList;
          this.loading = false;
        });
      } else {
        this._message.create('error', res.message);
      }
      this.loading = false;
    });
  }

  // 搜索商品
  searchGoods() {
    this.page = 1;
    this.getGoodsList();
  }

  reset() {
    this.selectedGroup = null;
    this.keyword = '';
    this.page = 1;
    this.getGoodsList();
  }

  goBack() {
    this.route.queryParams.subscribe(queryParams => {
      this.queryParams = queryParams;
    });
    this.router.navigate(['/member/group/list'], {
        queryParams: this.queryParams,
        relativeTo: this.route
      }
    );
  }

  changeRandomFreeGroup() {
    if (this.random_free) {
      if (this.random_free === 1) {
        this.validateForm.addControl('winners_number', this.fb.control(this.ghostData.winners_number, [this.winnerNumValidator], [this.integerValidators]));
        this.validateForm.addControl('free_scale', this.fb.control(this.ghostData.free_scale / 10, [Validators.required, Validators.max(100)], [this.integerValidators]));
        this.validateForm.addControl('head_win', this.fb.control(this.ghostData.head_win, [Validators.required]));
        this.validateForm.removeControl('head_free_price');
        this.validateForm.removeControl('is_give');
        this.validateForm.controls['group_type'].setValue(1);
      } else if (this.random_free === 2) {
        this.validateForm.removeControl('winners_number');
        this.validateForm.removeControl('free_scale');
        this.validateForm.removeControl('head_win');
        this.validateForm.addControl('head_free_price', this.fb.control(this.ghostData.head_free_price, [Validators.required]));
        this.validateForm.addControl('is_give', this.fb.control(this.ghostData.is_give, [Validators.required]));
        this.validateForm.controls['group_type'].setValue(4);
      }
    } else {
      this.validateForm.removeControl('winners_number');
      this.validateForm.removeControl('free_scale');
      this.validateForm.removeControl('head_win');
      this.validateForm.removeControl('head_free_price');
      this.validateForm.removeControl('is_give');
    }
    // if(this.random_free) {
    //   this.validateForm.addControl('winners_number',this.fb.control(this.ghostData.winners_number,[this.winnerNumValidator], [this.integerValidators]));
    //   this.validateForm.addControl('free_scale',this.fb.control(this.ghostData.free_scale / 10,[Validators.required, Validators.max(100)], [this.integerValidators]));
    //   this.validateForm.addControl('head_win',this.fb.control(this.ghostData.head_win,[Validators.required]));
    // } else {
    //   this.validateForm.removeControl('winners_number');
    //   this.validateForm.removeControl('free_scale');
    //   this.validateForm.removeControl('head_win');
    // }
  }

  _submitForm() {
    // 如果不是免单团，取消免单中的字段
    if (this.random_free === 1) {
      this.validateForm.value['head_win'] = this.validateForm.value['head_win'] ? 1 : 0;
      this.validateForm.value['free_scale'] = this.validateForm.value['free_scale'] / 100;
    }
    if (this.random_free === 2) {
      this.validateForm.value['is_give'] = this.validateForm.value['is_give'] ? 1 : 0;
    }

    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    // 验证是否选择sku
    if (!this.hasCheckedSku) {
      return false;
    }
    if (this.validateForm.valid) {
      this.validateForm.value['activity_goods_prize'] = JSON.stringify(this.activity_goods_prize);
      this.validateForm.value['start_date'] = moment(this.validateForm.value.start_date).format('YYYY-MM-DD');
      this.validateForm.value['end_date'] = moment(this.validateForm.value.end_date).format('YYYY-MM-DD');
      this.validateForm.value['new_offer'] = this.validateForm.value['new_offer'] ? 1 : 0;
      this._isSpinning = true;
      this.groupService.postEditGroup(this.validateForm.value).subscribe(res => {
        if (res.code === 2000) {
          const nowTime = new Date().getTime();
          const startTime = new Date(this.validateForm.value['start_date']).getTime();
          this._message.create('success', '修改拼团成功');
          this.route.queryParams.subscribe(queryParams => {
            this.queryParams = queryParams;
          });
          // let status = window.localStorage.getItem('status');
          let stage = null;
          if (this.saveStatus == '1') {
            stage = nowTime < startTime ? 1 : 2;
          } else if (this.saveStatus == '2') {
            stage = 4;
          } else {
            stage = this.stage;
          }
          this.router.navigate(['/member/group/list'], {
            queryParams: {
              type: this.queryParams.type,
              stage: stage
            },
            relativeTo: this.route
          });
        } else {
          this._message.create('error', res.message);
        }
        this._isSpinning = false;
      });
    }
  }
}
